package com.fly.code.process;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.operation.IRunnableWithProgress;

import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.FileOutConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.TemplateConfig;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.converts.OracleTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.keta.generate.core.GenerateFactory;
import com.keta.generate.util.Resources;
import com.keta.generate.util.StringUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * MybatisPlusRunProgress
 * 
 * @author 00fly
 * @version [版本号, 2017-7-25]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Slf4j
public class MybatisPlus2RunProgress implements IRunnableWithProgress
{
    private String driver;
    
    private String dburl;
    
    private String username;
    
    private String password;
    
    private String packName;
    
    private String projectDir;
    
    private String[] tabName;
    
    String prefix;
    
    String codeType;
    
    public MybatisPlus2RunProgress(String driver, String dburl, String username, String password, String packName, String projectDir, String[] tabName, String prefix, String codeType)
    {
        super();
        this.driver = driver;
        this.dburl = dburl;
        this.username = username;
        this.password = password;
        this.packName = packName;
        this.projectDir = projectDir;
        this.tabName = tabName;
        new File(projectDir + "src\\").mkdirs();
        this.prefix = prefix;
        this.codeType = codeType;
    }
    
    @Override
    public void run(IProgressMonitor monitor)
        throws InvocationTargetException, InterruptedException
    {
        // 在当前目录，创建并运行脚本
        try
        {
            monitor.beginTask("生成代码", IProgressMonitor.UNKNOWN);
            monitor.subTask("自动生成DAO、Map、MODEL 代码中......");
            creatAndRunMyBatisPlus(driver, dburl, username, password, packName, projectDir, tabName);
            monitor.done();
        }
        catch (Exception e)
        {
            log.error(e.getMessage());
            throw new InvocationTargetException(e.getCause(), e.getMessage());
        }
    }
    
    // 运行 MyBatis 代码创建程序
    private void creatAndRunMyBatisPlus(String driver, String dburl, String username, String password, String packName, String projectSrcDir, String[] tabName)
        throws Exception
    {
        AutoGenerator mpg = new AutoGenerator();
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(projectDir + "src/main/java/");
        gc.setFileOverride(true);
        gc.setActiveRecord(false);
        gc.setEnableCache(false);// XML 二级缓存
        gc.setBaseResultMap(true);// XML ResultMap
        gc.setBaseColumnList(true);// XML columList
        gc.setAuthor("00fly");
        // 自定义文件命名，注意 %s 会自动填充表实体属性！
        gc.setMapperName("%sDao");
        gc.setXmlName("%sDao");
        gc.setServiceName("%sService");
        gc.setServiceImplName("%sServiceImpl");
        gc.setControllerName("%sController");
        mpg.setGlobalConfig(gc);
        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        if ("com.mysql.jdbc.Driver".equals(driver))
        {
            dsc.setDbType(DbType.MYSQL);
            dsc.setTypeConvert(new MySqlTypeConvert()
            {
                // 自定义数据库表字段类型转换【可选】
                @Override
                public DbColumnType processTypeConvert(String fieldType)
                {
                    return super.processTypeConvert(fieldType);
                }
            });
        }
        else
        {
            dsc.setDbType(DbType.ORACLE);
            dsc.setTypeConvert(new OracleTypeConvert()
            {
                // 自定义数据库表字段类型转换【可选】
                @Override
                public DbColumnType processTypeConvert(String fieldType)
                {
                    return super.processTypeConvert(fieldType);
                }
            });
        }
        dsc.setDriverName(driver);
        dsc.setUsername(username);
        dsc.setPassword(password);
        dsc.setUrl(dburl);
        mpg.setDataSource(dsc);
        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        // strategy.setCapitalMode(true);// 全局大写命名 ORACLE 注意
        strategy.setTablePrefix(new String[] {prefix});// 此处可以修改为您的表前缀
        strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
        strategy.setInclude(tabName);// 需要生成的表
        strategy.setSuperControllerClass("com.fly.common.BaseController");
        mpg.setStrategy(strategy);
        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent(StringUtils.substringBeforeLast(packName, "."));
        pc.setModuleName(StringUtils.substringAfterLast(packName, "."));
        mpg.setPackageInfo(pc);
        // 注入自定义配置，可以在 VM 中使用 cfg.abc 【可无】
        InjectionConfig cfg = new InjectionConfig()
        {
            @Override
            public void initMap()
            {
                Map<String, Object> map = new HashMap<>(1);
                map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
                this.setMap(map);
            }
        };
        // jsp 生成
        List<FileOutConfig> focList = new ArrayList<>();
        focList.add(new FileOutConfig("/templates/index.jsp.vm")
        {
            @Override
            public String outputFile(TableInfo tableInfo)
            {
                return projectDir + "src/main/webapp/WEB-INF/pages/" + tableInfo.getEntityPath() + "/index.jsp";
            }
        });
        focList.add(new FileOutConfig("/templates/save.jsp.vm")
        {
            @Override
            public String outputFile(TableInfo tableInfo)
            {
                return projectDir + "src/main/webapp/WEB-INF/pages/" + tableInfo.getEntityPath() + "/save.jsp";
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        // 调整 xml 生成目录演示
        focList.add(new FileOutConfig("/templates/mapper.xml.vm")
        {
            @Override
            public String outputFile(TableInfo tableInfo)
            {
                return projectDir + "src/main/resources/mybatis/mapper/" + tableInfo.getEntityName() + ".xml";
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        // 关闭默认 xml 生成，调整生成 至 根目录
        TemplateConfig tc = new TemplateConfig();
        tc.setXml(null);
        mpg.setTemplate(tc);
        // 执行生成
        mpg.execute();
        // 生成模板下的文件
        for (String tableName : tabName)
        {
            String className;
            if (StringUtils.isEmpty(prefix))
            {
                className = StringUtil.camelCase(tableName, true);
            }
            else
            {
                className = StringUtil.camelCase(tableName.replaceAll("(?i)^" + prefix, ""), true);
            }
            Resources.init(driver, dburl, username, password, tableName, packName, projectDir, className, codeType);
            GenerateFactory factory = new GenerateFactory();
            factory.genJavaTemplate();
        }
    }
}
